package org.example.system.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.example.system.entity.Concern;
import org.example.system.entity.User;
import org.example.system.service.ConcernService;
import org.example.system.service.UserService;
import org.example.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 关注控制层
 */
@RestController
@Slf4j
@RequestMapping("/app/concern")
public class ConcerController {

    @Autowired
    private ConcernService concernService;
    @Autowired
    private UserService userService;

    /**
     * 按分页查询联查用户表
     * @param concern
     * @return
     */
    @GetMapping("/list")
    public R list(Concern concern){
        IPage<Concern> page = concernService.selectPage(concern);
        log.info("------------ ConcernController | list | selectPage | return : {} ", JSON.toJSONString(page));
        return R.ok(page);
    }

    /**
     * 添加关注
     * @param concern
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody Concern concern){
        log.info("--------- ConcernController | add | input : {}", JSON.toJSON(concern));
        int row = concernService.add(concern);
        if(row <= 0){
            return  R.fail("添加失败");
        }
        //关注用户添加一个关注
        User user = userService.getOne(concern.getUserId());
        user.setId(concern.getUserId());
        user.setConcern(user.getConcern() + 1);
        userService.update(user);
        //被关注用户添加一个粉丝
        User concernUser = userService.getOne(concern.getConcernUserId());
        concernUser.setId(concern.getConcernUserId());
        concernUser.setFans(concernUser.getFans() + 1);
        userService.update(concernUser);
        return R.ok("添加成功");
    }
    /**
     * 删除
     * @param ids
     * @return
     */
    @DeleteMapping( "/{ids}")
    public R delete(@PathVariable("ids") Long[] ids){
        log.info("--------- PostController | delete | input : {}", JSON.toJSON(ids));
        Concern concern = concernService.getOne(ids[0]);
        int row = concernService.deleteBatch(ids);
        if(row <= 0){
            return  R.fail("删除失败");
        }
        //关注用户减少一个关注
        User user = userService.getOne(concern.getUserId());
        user.setId(concern.getUserId());
        user.setConcern(user.getConcern() - 1);
        userService.update(user);
        //被关注用户减少一个粉丝
        User concernUser = userService.getOne(concern.getConcernUserId());
        concernUser.setId(concern.getConcernUserId());
        concernUser.setFans(concernUser.getFans() - 1);
        userService.update(concernUser);
        return R.ok("删除成功");
    }
}
